﻿using Css_VoteSys.Models.Database;
using Css_VoteSys.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Css_VoteSys.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class VoteInfoController : ControllerBase
    {
        private readonly Css_VoteSysContext _db;
        private readonly IVoteInfoService _VoteInfoService;

        public VoteInfoController(Css_VoteSysContext db, IVoteInfoService VoteInfoService) {
            _db = db;
            _VoteInfoService = VoteInfoService;
        }

        /// <summary>
        /// 投票接口
        /// </summary>
        /// <param name="ProjectId">投票项目id</param>
        /// <returns></returns>
        [HttpGet]
        public string GiveVote(int ProjectId) {
            DateTime now = DateTime.Now;
            DateTime currentDate = DateTime.Now.Date;
            var UserId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
            if (UserId == null) { return "请先登录"; }
            // 投票记录不存在，添加新记录
            if (_VoteInfoService.Is5Vote(ProjectId))
            {
                return "今日投票已达上线";
            }
            var voteInfo = _db.VoteInfos
                      .FirstOrDefault(v => v.UserId == Convert.ToInt32(UserId) && v.ProjectId == ProjectId && v.VoteTime == currentDate);
            if (voteInfo != null)
            {
                // 投票记录已经存在，增加票数
                voteInfo.VoteNum++;
            }
            else
            {
                _db.VoteInfos.Add(new VoteInfo
                {
                    UserId = Convert.ToInt32(UserId),
                    ProjectId = ProjectId,
                    VoteNum = 1,
                    VoteTime = currentDate
                });
            }
            //保存更改
            var row = _db.SaveChanges();
            if (row > 0)
                return "投票成功";
            return "投票失败";
            
        }
    }
}
